<template>
    <a-modal
      :bodyStyle="bodyStyle"
      :title="title"
      :visible="visible"
      :confirmLoading="confirmLoading"
      :destroyOnClose="true"
      :maskClosable="false"
      @ok="handleOk"
      @cancel="handleCancel"
    >
      <a-form layout='vertical' :form="form">
        <a-form-item  class="a-form-item" v-bind="formItemLayout" label="头像">
          <a-upload
            listType="picture-card"
            class="avatar-uploader"
            :showUploadList="false"
            :beforeUpload="beforeUpload"
            v-decorator="['picture',{rules: [{ required: false, message: '请选择头像!' }]}]"
          >
            <a-avatar shape="square" :size="90" icon="user" v-if="photoUrl" :src="photoUrl"/>
            <div v-else>
                <a-icon :type="loading ? 'loading' : 'plus'" />
                <div class="ant-upload-text">Upload</div>
            </div>
          </a-upload>
        </a-form-item>
        <a-form-item  class="a-form-item" v-bind="formItemLayout" label="帐号">
          <a-input
            v-decorator="[
              'username',
              {
                rules: [{ required: true, message: '请输入4到16位（字母，数字)的帐号!' , pattern: /^[a-zA-Z0-9]{4,16}$/ }],
              }
            ]"
            placeholder="请输入帐号"
          />
        </a-form-item>
        <a-form-item  class="a-form-item" v-bind="formItemLayout" label="昵称">
          <a-input
            v-decorator="[
              'emojiNickName',
              {
                rules: [{ required: true, message: '请输入昵称!' }],
              }
            ]"
            placeholder="请输入昵称"
          />
        </a-form-item>
        <a-form-item  class="a-form-item" v-bind="formItemLayout" label="手机号">
          <a-input
            v-decorator="[
              'telephone',
              {
                rules: [{ required: false, message: '请输入正确的手机号!', pattern: /^1[34578]\d{9}$/ }],
              }
            ]"
            placeholder="请输入手机号"
          />
        </a-form-item>
        <a-form-item class="a-form-item" v-bind="formItemLayout" label="性别">
          <a-radio-group v-decorator="['sex']">
            <a-radio :value="1">
              男
            </a-radio>
            <a-radio :value="2">
              女
            </a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item class="a-form-item" v-bind="formItemLayout" label="状态">
          <a-checkbox
            :checked="disabled"
            @change="onChangeDisabled"
            v-decorator="[
              'disabled',
              {
                rules: [{ required: false }],
              }
            ]"
          >禁用</a-checkbox>
        </a-form-item>
        <a-form-item>
          <a-input type="hidden" v-decorator="['id', {}]"/>
          <a-input type="hidden" v-decorator="['type', {}]"/>
        </a-form-item>
      </a-form>
    </a-modal>
</template>
<script>
import Vue from 'vue'
import api from '@/core/Api'
import serv from './MembershipService'
import { Form, Upload, Checkbox, Input, Modal, Radio } from 'ant-design-vue'
// Vue.component(Select.name, Select)
// Vue.component(Select.Option.name, Select.Option)
Vue.component(Radio.name, Radio)
Vue.component(Radio.Group.name, Radio.Group)
Vue.component(Form.name, Form)
Vue.component(Form.Item.name, Form.Item)
Vue.component(Upload.name, Upload)
Vue.component(Checkbox.name, Checkbox)
Vue.component(Input.name, Input)
Vue.component(Modal.name, Modal)
export default {
  beforeCreate () {
    this.form = this.$form.createForm(this)
  },
  created () {

  },
  data () {
    return {
      confirmLoading: false,
      formItemLayout: {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 4 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 20 }
        }
      },
      bodyStyle: { height: 400 },
      productTypes: [],
      loading: false,
      photoUrl: '',
      disabled: false,
      sexChecked: false,
      treeData: []
    }
  },
  props: {
    title: {
      type: String,
      required: true
    },
    visible: {
      type: Boolean,
      default: false
    },
    record: {
      type: Object,
      default () {
        return {}
      }
    }
  },
  watch: {
    visible: function (nvalue) {
      // !nvalue || this.getTree()
      if (nvalue && Object.keys(this.record).length > 0) {
        console.log(this.record)
        setTimeout(() => {
          this.form.setFieldsValue(this.record)
        }, 10)
        this.disabled = this.record.disabled === 1
        this.sexChecked = this.record.sex === 1
        this.photoUrl = this.record.photoUrl
      } else {
        this.photoUrl = ''
        this.disabled = false
        this.sexChecked = false
        this.confirmLoading = false
      }
    }
  },
  methods: {
    handleOk () {
      const form = this.form
      form.validateFields((err, values) => {
        if (err) {
          return
        }
        values.disabled = values.disabled ? 1 : 0
        let formData = new FormData()
        for (let key in values) {
          let value = values[key]
          if (value) formData.append(key, value.file ? value.file : value)
        }
        this.confirmLoading = true
        serv.save(formData).then(res => {
          this.confirmLoading = false
          if (res.data.code === 0) {
            form.resetFields()
            this.$emit('ok', formData.get('id'))
          } else {
            this.$message.error(res.data.msg)
          }
        })
      })
    },
    handleCancel (e) {
      this.$emit('cancel')
    },
    beforeUpload (file) {
      const isJPG = file.type === 'image/jpeg'
      if (!isJPG) {
        this.$message.error('You can only upload JPG file!')
      }
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isLt2M) {
        this.$message.error('Image must smaller than 2MB!')
      }
      const r = isJPG && isLt2M
      if (r) {
        api.getBase64(file, (imageUrl) => {
          this.photoUrl = imageUrl
          this.loading = false
        })
      }
      return false
    },
    onChangeDisabled (e) {
      this.disabled = e.target.checked
    },
    onChangeSex (e) {
      this.sexChecked = e.target.checked
    }
  }
}
</script>

<style scoped>
img {
  max-width: 100%;
}

.a-form-item {
  margin-bottom: 0px;
}
</style>
